import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import authService from '../services/authService';
import { validateEmail, validateName, validatePhone, validateVerificationCode, calculatePasswordStrength, getPasswordStrengthText, generateMockVerificationCode } from '../utils/validators';
import { REGISTER_FORM_FIELDS } from '../constants/formFields';
import CaptchaModal from './CaptchaModal';
import './FormStyles.css';

const RegisterForm = ({ switchMode }) => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [registerType, setRegisterType] = useState('email'); // 'email' or 'phone'
  const [formData, setFormData] = useState({
    [REGISTER_FORM_FIELDS.NAME]: '',
    [REGISTER_FORM_FIELDS.EMAIL]: '',
    [REGISTER_FORM_FIELDS.PHONE]: '',
    [REGISTER_FORM_FIELDS.PASSWORD]: '',
    [REGISTER_FORM_FIELDS.CONFIRM_PASSWORD]: '',
    [REGISTER_FORM_FIELDS.VERIFICATION_CODE]: '',
    [REGISTER_FORM_FIELDS.AGREE_TO_TERMS]: false,
    [REGISTER_FORM_FIELDS.REGISTER_TYPE]: 'email'
  });
  
  const [errors, setErrors] = useState({});
  const [isLoading, setIsLoading] = useState(false);
  const [passwordStrength, setPasswordStrength] = useState(0);
  const [countdown, setCountdown] = useState(0);
  const [mockVerificationCode, setMockVerificationCode] = useState('');
  const [isCaptchaValid, setIsCaptchaValid] = useState(false);
  const [showCaptchaModal, setShowCaptchaModal] = useState(false);

  const handleChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value
    }));
    
    // Clear error when user starts typing
    if (errors[name]) {
      setErrors(prev => ({ ...prev, [name]: '' }));
    }
    
    // Check password strength
    if (name === REGISTER_FORM_FIELDS.PASSWORD) {
      setPasswordStrength(calculatePasswordStrength(value));
    }
  };

  useEffect(() => {
    let timer;
    if (countdown > 0) {
      timer = setTimeout(() => setCountdown(countdown - 1), 1000);
    }
    return () => clearTimeout(timer);
  }, [countdown]);

  const handleRegisterTypeChange = (type) => {
    setRegisterType(type);
    setFormData(prev => ({
      ...prev,
      [REGISTER_FORM_FIELDS.REGISTER_TYPE]: type,
      [REGISTER_FORM_FIELDS.EMAIL]: '',
      [REGISTER_FORM_FIELDS.PHONE]: '',
      [REGISTER_FORM_FIELDS.VERIFICATION_CODE]: ''
    }));
    setErrors({});
    setIsCaptchaValid(false);
  };

  const sendVerificationCode = () => {
    if (registerType === 'phone') {
      if (!formData[REGISTER_FORM_FIELDS.PHONE]) {
        setErrors({ [REGISTER_FORM_FIELDS.PHONE]: t('registerForm.phoneRequired') });
        return;
      }
      if (!validatePhone(formData[REGISTER_FORM_FIELDS.PHONE])) {
        setErrors({ [REGISTER_FORM_FIELDS.PHONE]: t('registerForm.phoneInvalid') });
        return;
      }
    }
    
    // Generate mock verification code
    const code = generateMockVerificationCode();
    setMockVerificationCode(code);
    
    // In a real app, this would send the code via SMS
    alert(`${t('registerForm.verificationCodeSent')}: ${code}`);
    
    // Start countdown
    setCountdown(60);
  };

  const validateForm = () => {
    const newErrors = {};
    
    if (!formData[REGISTER_FORM_FIELDS.NAME]) {
      newErrors[REGISTER_FORM_FIELDS.NAME] = t('registerForm.nameRequired');
    } else if (!validateName(formData[REGISTER_FORM_FIELDS.NAME])) {
      newErrors[REGISTER_FORM_FIELDS.NAME] = t('registerForm.nameMinLength');
    }
    
    if (registerType === 'email') {
      if (!formData[REGISTER_FORM_FIELDS.EMAIL]) {
        newErrors[REGISTER_FORM_FIELDS.EMAIL] = t('registerForm.emailRequired');
      } else if (!validateEmail(formData[REGISTER_FORM_FIELDS.EMAIL])) {
        newErrors[REGISTER_FORM_FIELDS.EMAIL] = t('registerForm.emailInvalid');
      }
    } else {
      if (!formData[REGISTER_FORM_FIELDS.PHONE]) {
        newErrors[REGISTER_FORM_FIELDS.PHONE] = t('registerForm.phoneRequired');
      } else if (!validatePhone(formData[REGISTER_FORM_FIELDS.PHONE])) {
        newErrors[REGISTER_FORM_FIELDS.PHONE] = t('registerForm.phoneInvalid');
      }
      
      if (!formData[REGISTER_FORM_FIELDS.VERIFICATION_CODE]) {
        newErrors[REGISTER_FORM_FIELDS.VERIFICATION_CODE] = t('registerForm.verificationCodeRequired');
      } else if (!validateVerificationCode(formData[REGISTER_FORM_FIELDS.VERIFICATION_CODE])) {
        newErrors[REGISTER_FORM_FIELDS.VERIFICATION_CODE] = t('registerForm.verificationCodeInvalid');
      } else if (formData[REGISTER_FORM_FIELDS.VERIFICATION_CODE] !== mockVerificationCode) {
        newErrors[REGISTER_FORM_FIELDS.VERIFICATION_CODE] = t('registerForm.verificationCodeInvalid');
      }
    }
    
    if (!formData[REGISTER_FORM_FIELDS.PASSWORD]) {
      newErrors[REGISTER_FORM_FIELDS.PASSWORD] = t('registerForm.passwordRequired');
    } else if (formData[REGISTER_FORM_FIELDS.PASSWORD].length < 8) {
      newErrors[REGISTER_FORM_FIELDS.PASSWORD] = t('registerForm.passwordMinLength');
    }
    
    if (!formData[REGISTER_FORM_FIELDS.CONFIRM_PASSWORD]) {
      newErrors[REGISTER_FORM_FIELDS.CONFIRM_PASSWORD] = t('registerForm.confirmPasswordRequired');
    } else if (formData[REGISTER_FORM_FIELDS.PASSWORD] !== formData[REGISTER_FORM_FIELDS.CONFIRM_PASSWORD]) {
      newErrors[REGISTER_FORM_FIELDS.CONFIRM_PASSWORD] = t('registerForm.passwordMismatch');
    }
    
    if (!formData[REGISTER_FORM_FIELDS.AGREE_TO_TERMS]) {
      newErrors[REGISTER_FORM_FIELDS.AGREE_TO_TERMS] = t('registerForm.termsRequired');
    }
    
    // 验证码验证将在弹出模态框中进行，这里不再检查
    
    return newErrors;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const newErrors = validateForm();
    
    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
      return;
    }
    
    // 显示验证码模态框而不是直接提交
    setShowCaptchaModal(true);
  };

  const handleCaptchaVerified = () => {
    setIsCaptchaValid(true);
    setIsLoading(true);
    
    // Simulate registration process without API call
    setTimeout(() => {
      // Store a mock token to simulate authentication
      localStorage.setItem('mockAuthToken', 'demo-token');
      
      let userData;
      if (registerType === 'email') {
        userData = {
          name: formData[REGISTER_FORM_FIELDS.NAME],
          email: formData[REGISTER_FORM_FIELDS.EMAIL]
        };
      } else {
        userData = {
          name: formData[REGISTER_FORM_FIELDS.NAME],
          phone: formData[REGISTER_FORM_FIELDS.PHONE]
        };
      }
      
      localStorage.setItem('mockUser', JSON.stringify(userData));
      
      setIsLoading(false);
      setShowCaptchaModal(false);
      alert(t('registerForm.registerSuccess'));
      
      // Redirect to landing page
      navigate('/');
    }, 1500);
  };

  const strengthText = getPasswordStrengthText(passwordStrength, t);

  return (
    <form className="auth-form" onSubmit={handleSubmit}>
      {errors.general && (
        <div className="error-message general-error">
          {errors.general}
        </div>
      )}
      
      {/* Register Type Toggle */}
      <div className={`login-type-toggle ${registerType === 'phone' ? 'phone-active' : ''}`}>
        <button
          type="button"
          className={`toggle-btn ${registerType === 'email' ? 'active' : ''}`}
          onClick={() => handleRegisterTypeChange('email')}
        >
          {t('registerForm.registerWithEmail')}
        </button>
        <button
          type="button"
          className={`toggle-btn ${registerType === 'phone' ? 'active' : ''}`}
          onClick={() => handleRegisterTypeChange('phone')}
        >
          {t('registerForm.registerWithPhone')}
        </button>
      </div>
      
      <div className="form-group">
        <label htmlFor={REGISTER_FORM_FIELDS.NAME} className="form-label">{t('registerForm.nameLabel')}</label>
        <div className="input-wrapper">
          <input
            type="text"
            id={REGISTER_FORM_FIELDS.NAME}
            name={REGISTER_FORM_FIELDS.NAME}
            className={`form-input ${errors[REGISTER_FORM_FIELDS.NAME] ? 'error' : ''}`}
            placeholder={t('registerForm.namePlaceholder')}
            value={formData[REGISTER_FORM_FIELDS.NAME]}
            onChange={handleChange}
            disabled={isLoading}
          />
          {errors[REGISTER_FORM_FIELDS.NAME] && (
            <span className="error-icon">⚠️</span>
          )}
        </div>
        {errors[REGISTER_FORM_FIELDS.NAME] && (
          <span className="error-message">{errors[REGISTER_FORM_FIELDS.NAME]}</span>
        )}
      </div>
      
      {registerType === 'email' ? (
        <div className="form-group">
          <label htmlFor={REGISTER_FORM_FIELDS.EMAIL} className="form-label">{t('registerForm.emailLabel')}</label>
          <div className="input-wrapper">
            <input
              type="email"
              id={REGISTER_FORM_FIELDS.EMAIL}
              name={REGISTER_FORM_FIELDS.EMAIL}
              className={`form-input ${errors[REGISTER_FORM_FIELDS.EMAIL] ? 'error' : ''}`}
              placeholder={t('registerForm.emailPlaceholder')}
              value={formData[REGISTER_FORM_FIELDS.EMAIL]}
              onChange={handleChange}
              disabled={isLoading}
            />
            {errors[REGISTER_FORM_FIELDS.EMAIL] && (
              <span className="error-icon">⚠️</span>
            )}
          </div>
          {errors[REGISTER_FORM_FIELDS.EMAIL] && (
            <span className="error-message">{errors[REGISTER_FORM_FIELDS.EMAIL]}</span>
          )}
        </div>
      ) : (
        <>
          <div className="form-group">
            <label htmlFor={REGISTER_FORM_FIELDS.PHONE} className="form-label">{t('registerForm.phoneLabel')}</label>
            <div className="input-wrapper">
              <input
                type="tel"
                id={REGISTER_FORM_FIELDS.PHONE}
                name={REGISTER_FORM_FIELDS.PHONE}
                className={`form-input ${errors[REGISTER_FORM_FIELDS.PHONE] ? 'error' : ''}`}
                placeholder={t('registerForm.phonePlaceholder')}
                value={formData[REGISTER_FORM_FIELDS.PHONE]}
                onChange={handleChange}
                disabled={isLoading}
              />
              {errors[REGISTER_FORM_FIELDS.PHONE] && (
                <span className="error-icon">⚠️</span>
              )}
            </div>
            {errors[REGISTER_FORM_FIELDS.PHONE] && (
              <span className="error-message">{errors[REGISTER_FORM_FIELDS.PHONE]}</span>
            )}
          </div>
          
          <div className="form-group">
            <label htmlFor={REGISTER_FORM_FIELDS.VERIFICATION_CODE} className="form-label">{t('registerForm.verificationCodeLabel')}</label>
            <div className="input-wrapper with-button">
              <input
                type="text"
                id={REGISTER_FORM_FIELDS.VERIFICATION_CODE}
                name={REGISTER_FORM_FIELDS.VERIFICATION_CODE}
                className={`form-input ${errors[REGISTER_FORM_FIELDS.VERIFICATION_CODE] ? 'error' : ''}`}
                placeholder={t('registerForm.verificationCodePlaceholder')}
                value={formData[REGISTER_FORM_FIELDS.VERIFICATION_CODE]}
                onChange={handleChange}
                disabled={isLoading}
                maxLength={6}
              />
              <button
                type="button"
                className="verification-code-btn"
                onClick={sendVerificationCode}
                disabled={isLoading || countdown > 0}
              >
                {countdown > 0 ? `${countdown} ${t('registerForm.seconds')}` : t('registerForm.sendVerificationCode')}
              </button>
              {errors[REGISTER_FORM_FIELDS.VERIFICATION_CODE] && (
                <span className="error-icon">⚠️</span>
              )}
            </div>
            {errors[REGISTER_FORM_FIELDS.VERIFICATION_CODE] && (
              <span className="error-message">{errors[REGISTER_FORM_FIELDS.VERIFICATION_CODE]}</span>
            )}
          </div>
        </>
      )}
      
      <div className="form-group">
        <label htmlFor={REGISTER_FORM_FIELDS.PASSWORD} className="form-label">{t('registerForm.passwordLabel')}</label>
        <div className="input-wrapper">
          <input
            type="password"
            id={REGISTER_FORM_FIELDS.PASSWORD}
            name={REGISTER_FORM_FIELDS.PASSWORD}
            className={`form-input ${errors[REGISTER_FORM_FIELDS.PASSWORD] ? 'error' : ''}`}
            placeholder={t('registerForm.passwordPlaceholder')}
            value={formData[REGISTER_FORM_FIELDS.PASSWORD]}
            onChange={handleChange}
            disabled={isLoading}
          />
          {errors[REGISTER_FORM_FIELDS.PASSWORD] && (
            <span className="error-icon">⚠️</span>
          )}
        </div>
        {errors[REGISTER_FORM_FIELDS.PASSWORD] && (
          <span className="error-message">{errors[REGISTER_FORM_FIELDS.PASSWORD]}</span>
        )}
        
        {formData[REGISTER_FORM_FIELDS.PASSWORD] && (
          <div className="password-strength">
            <div className="strength-bar">
              <div 
                className="strength-fill" 
                style={{ 
                  width: `${(passwordStrength / 4) * 100}%`,
                  backgroundColor: strengthText.color
                }}
              ></div>
            </div>
            <span 
              className="strength-text"
              style={{ color: strengthText.color }}
            >
              {strengthText.text}
            </span>
          </div>
        )}
      </div>
      
      <div className="form-group">
        <label htmlFor={REGISTER_FORM_FIELDS.CONFIRM_PASSWORD} className="form-label">{t('registerForm.confirmPasswordLabel')}</label>
        <div className="input-wrapper">
          <input
            type="password"
            id={REGISTER_FORM_FIELDS.CONFIRM_PASSWORD}
            name={REGISTER_FORM_FIELDS.CONFIRM_PASSWORD}
            className={`form-input ${errors[REGISTER_FORM_FIELDS.CONFIRM_PASSWORD] ? 'error' : ''}`}
            placeholder={t('registerForm.confirmPasswordPlaceholder')}
            value={formData[REGISTER_FORM_FIELDS.CONFIRM_PASSWORD]}
            onChange={handleChange}
            disabled={isLoading}
          />
          {errors[REGISTER_FORM_FIELDS.CONFIRM_PASSWORD] && (
            <span className="error-icon">⚠️</span>
          )}
        </div>
        {errors[REGISTER_FORM_FIELDS.CONFIRM_PASSWORD] && (
          <span className="error-message">{errors[REGISTER_FORM_FIELDS.CONFIRM_PASSWORD]}</span>
        )}
      </div>
      
      <div className="form-group">
        <label className="checkbox-label terms-label">
          <input
            type="checkbox"
            name={REGISTER_FORM_FIELDS.AGREE_TO_TERMS}
            checked={formData[REGISTER_FORM_FIELDS.AGREE_TO_TERMS]}
            onChange={handleChange}
            disabled={isLoading}
          />
          <span className="checkmark"></span>
          {t('registerForm.agreeToTerms')} <a href="#" className="terms-link">{t('registerForm.termsOfService')}</a> {t('registerForm.and')} <a href="#" className="terms-link">{t('registerForm.privacyPolicy')}</a>
        </label>
        {errors[REGISTER_FORM_FIELDS.AGREE_TO_TERMS] && (
          <span className="error-message">{errors[REGISTER_FORM_FIELDS.AGREE_TO_TERMS]}</span>
        )}
      </div>
      
      
      <button
        type="submit"
        className="submit-btn"
        disabled={isLoading}
      >
        {isLoading ? (
          <span className="loading-spinner"></span>
        ) : (
          t('registerForm.createAccountButton')
        )}
      </button>
      
      <div className="switch-auth">
        {t('registerForm.hasAccount')}
        <button 
          type="button" 
          className="switch-btn"
          onClick={switchMode}
          disabled={isLoading}
        >
          {t('registerForm.loginNow')}
        </button>
      </div>
      
      {/* Captcha Modal */}
      <CaptchaModal
        isOpen={showCaptchaModal}
        onClose={() => setShowCaptchaModal(false)}
        onVerify={handleCaptchaVerified}
        title={t('captcha.verification')}
      />
    </form>
  );
};

export default RegisterForm;